package org.xqh.study.google.guice;

import com.google.common.base.Joiner;
import com.google.inject.Binder;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.binder.LinkedBindingBuilder;
import com.google.inject.multibindings.MapBinder;

import java.util.Map;

/**
 * @ClassName Applets
 * @Description 封装 guice相关 注册绑定操作.
 * @Author xuqianghui
 * @Date 2022/5/23 20:43
 * @Version 1.0
 */
public class Applets {


    public static class AppletsRegister{
        private Binder binder;

        private AppletsRegister(Binder binder) {
            this.binder = binder;
        }

        public <T> LinkedBindingBuilder<MyApplet> named(String name) {
            return MapBinder.newMapBinder(binder, String.class, MyApplet.class).addBinding(name);
        }
    }

    public static AppletsRegister register(Binder binder) {
        return new AppletsRegister(binder);
    }

    public static MyApplet get(Injector injector, String name){
        //获取注入的 map实例
        Map<String, MyApplet> applets =
                injector.getInstance(Key.get(new TypeLiteral<Map<String, MyApplet>>(){}))
                ;
        if (!applets.containsKey(name)) {
            throw new IllegalArgumentException("Unable to find applet. Valid applet are "
                    + Joiner.on(", ").join(applets.keySet()));
        }
        return applets.get(name);
    }
}
